package wechat;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public class PostUtil {
    /** in milliseconds  连接超时的时间*/
    private final static int CONNECT_TIMEOUT = 5000;
    //字符串编码
    private final static String DEFAULT_ENCODING = "UTF-8";
    public static String postData(String urlStr, String data) throws IOException {
        return postData(urlStr, data, null);
    }

    public static String postData(String urlStr, String data, String contentType) throws IOException {
        BufferedReader reader = null;
        try {
            URL url = new URL(urlStr);
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            conn.setConnectTimeout(CONNECT_TIMEOUT);
            conn.setReadTimeout(CONNECT_TIMEOUT);
            if (contentType != null) {
                conn.setRequestProperty("content-type", contentType);
            }
            OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), DEFAULT_ENCODING);
            if (data == null){
                data = "";
            }
            writer.write(data);
            writer.flush();
            writer.close();

            reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), DEFAULT_ENCODING));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
                sb.append("\r\n");
            }
            return sb.toString();
        } catch (IOException e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
            throw e;
        } finally {
            try {
                if (reader != null){
                    reader.close();
                }
            } catch (IOException e) {
            }
        }
    }



    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url    发送请求的 URL
     * @param params 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     * @throws Exception
     */
    public static String sendPost(String url, Map<String, String> params, String encode) throws Exception {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("content-type", "application/x-www-form-urlencoded;");

            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());


            StringBuffer stringBuffer = new StringBuffer();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                try {
                    stringBuffer
                            .append(entry.getKey())
                            .append("=")
                            .append(URLEncoder.encode(entry.getValue(), encode))
                            .append("&");

                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }

            System.out.println(stringBuffer.toString());
            // 发送请求参数
            out.print(stringBuffer.toString());
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), encode));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
            throw e;
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        System.out.println(result);
        return result;
    }

    /**
     * @param
     */
    public static String sendGet(String reqUrl, Map<String, String> params, String encode) {

        URL url = null;
        OutputStream outStrm = null;
        InputStream inStrm = null;
        BufferedReader br = null;
        String result = null;
        String temp = null;
        HttpURLConnection httpurlconnection = null;
        try {
            StringBuffer stringBuffer = new StringBuffer();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                try {
                    stringBuffer
                            .append(entry.getKey())
                            .append("=")
                            .append(URLEncoder.encode(entry.getValue(), encode))
                            .append("&");

                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            if (params.size() > 0) {
                stringBuffer.deleteCharAt(stringBuffer.length() - 1);
            }
            url = new URL(reqUrl + "?" + stringBuffer.toString());
            httpurlconnection = (HttpURLConnection) url.openConnection();
            httpurlconnection.setDoInput(true);
            httpurlconnection.setDoOutput(true);
            httpurlconnection.setUseCaches(false);
            httpurlconnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;");
            httpurlconnection.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
            httpurlconnection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");
            httpurlconnection.setRequestProperty("Connection", "keep-alive");
            httpurlconnection.setRequestProperty("Host", "v2.neeq.com.cn");
            httpurlconnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:42.0) Gecko/20100101 Firefox/42.0");
            httpurlconnection.setRequestProperty("X-Requested-With", "XMLHttpRequest");

            httpurlconnection.setRequestMethod("GET");
            System.out.println("httpurlconnection==" + httpurlconnection);
            httpurlconnection.connect();
            outStrm = httpurlconnection.getOutputStream();
            outStrm.flush();
            outStrm.close();
            inStrm = httpurlconnection.getInputStream();
            br = new BufferedReader(new InputStreamReader(
                    inStrm, "UTF-8"));
            while ((temp = br.readLine()) != null) {
                result = result + temp;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                inStrm.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "";
    }

    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url   发送请求的URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, java.util.List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
//                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url 发送请求的URL
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url;
            URL realUrl = new URL(urlNameString);
            System.out.println("请求url为" + url);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, java.util.List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
//                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            System.out.println("url为" + url + "的返回结果为" + result);
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    /**
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
		/*String url = "http://api.shuyuanwl.com:8080/api/sms/send?";
		Map<String, String> params = new HashMap<String, String>();
		params.put("account", "tjhthy@tjhthy");
		params.put("password", "sh64MT92");
		params.put("mobiles", "17600901605");
		params.put("content", "8888 手机注册验证码，请于60秒内输入，请勿告诉任何人");
		
		
		String result = PostUtil.sendPost(url, params, "UTF-8");*/

        String url = "http://111.230.174.143:8090/apple/open/openMerc?";
        Map<String, String> params = new HashMap<String, String>();
        params.put("serverId", "20001");
        params.put("account", "12345678988");
        params.put("mercCode", "300003");
        params.put("password", "111111");
        params.put("name", "商户1");


        String result = PostUtil.sendPost(url, params, "UTF-8");
        System.out.println(result);


    }


}
